const Koa = require('koa');
const app = new Koa();

const KoaRouter = require('koa-router');
const router = new KoaRouter();

const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

const { query } = require('./util');

// CRUD 接口
router.post('/invoices', async (ctx) => {
    // 解构参数
    const { type, name, sh, email, is_zy, is_default } = ctx.request.body;
    // 保存数据库
    const res = await query(
        'insert into invoice (type, name, sh, email, is_zy, is_default) values (?, ?, ?, ?, ?, ?)',
        [type, name, sh, email, is_zy, is_default],
    );

    // 判断是否添加成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: '发票添加失败，请稍后再试！',
        };
        return;
    }

    // 返回成功响应
    ctx.body = {
        code: 201,
        message: '发票添加成功',
    };
});
router.get('/invoices', async (ctx) => {
    const res = await query('select * from invoice');
    ctx.body = {
        code: 200,
        data: res,
        message: '获取列表成功',
    };
});
router.put('/invoices/:id', async (ctx) => {});
router.delete('/invoices/:id', async (ctx) => {});

// 启用路由
app.use(router.routes());

// 监听端口，提供服务
app.listen(3000, () => {
    console.log('Koa server listening at http://localhost:3000');
});
